<?php
/*********************************************************************************
 *用户注册
 * error码
 *        100 ：openid数据为空
 *        101 ：创建用户出错
 *        102 ：创建用户表出错
 *        103 ：openid未注册
 *        104 ：openid已注册
 *        200 : 成功
 **********************************************************************************/
$openid = $_POST["openid"];
$code = $_POST["code"];
if(isset($openid)){
    switch ($code) {
        case 'censor':
            $topic = find_data($openid);
            if($topic == "vacuous"){
                $a = array(
                    "error"=>103,
                    "state"=>"未注册"
                );
                echo json_encode($a);
            }else{
                $a = array(
                    "error"=>200,
                    "state"=>$topic
                );
                echo json_encode($a);
            }
        break;
        case 'egister':
            if(create_user($openid) == "success"){
                if(establish_uerlibrary($openid) == "success"){
                    $a = array(
                        "error"=>200,
                        "state"=>find_data($openid)
                    );
                    echo json_encode($a);
                }else{
                    echo json_encode(judge(102));
                }
            }else{
                echo json_encode(judge(101));
            }
        break;
}
}else{
    $a = array(
        "error"=>100,
        "state"=>"无效openid或空"
    );
    echo json_encode($a);
}


//连接数据库
function connect_database($database="user_database"){
    $conn = new mysqli("localhost", "root", "1314", $database);
    if ($conn->connect_error) {// 检测连接
        die("内部错误： " . $conn->connect_error);
    }
    return $conn;
}
//创建用户数据表
function createuserlibrary($userlibrary){ //$library=库 连接库
    $conn = connect_database();
    $sql = "CREATE TABLE $userlibrary (     /* 使用 sql 创建数据表*/
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    applianceId INT(128) NOT NULL,  /* 设备序列号*/
    add_time VARCHAR(30) NOT NULL,     /* 添加时间*/
    device_name TEXT(128) NOT NULL,    /* 设备名*/
    groupName TEXT(128) NOT NULL,      /* 位置*/
    applianceTypes TEXT(128) NOT NULL, /* 设备类型*/ 
    devices_value TEXT(128) NOT NULL,  /* 设备状态 */
    image_1 TEXT(128) NOT NULL,        /* 设备图标路径，微信小程序使用 */
    image_2 TEXT(128) NOT NULL,        /* 设备在线状态图标路径，微信小程序使用 */
    lamp TEXT(128) NOT NULL,           /* 设备控制函数，微信小程序使用 */
    device_time TEXT(128) NOT NULL,    /* 设备上报时间 */
    reg_date TIMESTAMP)";
    if ($conn->query($sql) === TRUE) {
        return "success";
    } else {
        return $conn->error;
    }
    $conn->close();
}
//查找用户数据
function find_data($openid){
    $conn = connect_database();
    $sql = "SELECT userlibrary FROM openidlibrary WHERE openid_wx='$openid'"; //SELECT=列  FPOM=表 WHERE=条件
    $result = mysqli_query($conn,$sql);  //查找数组
    $result = mysqli_fetch_assoc($result); //获取数组
    if(isset($result))
    {
        //$dax = implode('',$result);//数组转字符
        return implode('',$result);
    }else {
    return "vacuous";
    }
    $conn->close();
}



//创建用户
function create_user($openid){
    //echo $a;
    if(find_data($openid) == "vacuous"){
        $uer = makeCardPassword();
        $uer = "yf".$uer;
        $conn = connect_database();
        $sql = "INSERT INTO openidlibrary (openid_wx,userlibrary) VALUES ('$openid','$uer')";
        mysqli_select_db( $conn, 'RUNOOB' );
        $retval = mysqli_query( $conn, $sql );
        if(!$retval){
            //die('无法插入数据: ' . mysqli_error($conn));
            return mysqli_error($conn);
        }else{
            //echo "数据插入成功\n";
            return "success";
        }
        $conn->close();
    }else{
        return 1;
    }
}

//创建用户表
function establish_uerlibrary($openid){
    return createuserlibrary(find_data($openid));
}


//随机生成不重复的8位字符
function makeCardPassword(){
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    ) ;
    return $d;
}
function judge($a){
    if($a == 0){
        $Success = array(
            "error"=>$a,
            "state"=>"success"
        );
        return $Success;
    }else{
        $failure = array(
            "error"=>$a,
            "state"=>"failure"  
        );
        return $failure;
    }
}


//创建openidlibrary数据表
function cre(){ //$library=库 连接库
    $conn = connect_database();
    $sql = "CREATE TABLE openidlibrary (     /* 使用 sql 创建数据表*/
    Id INT(128) PRIMARY KEY,  /* 设备序列号*/
    openid_wx TEXT(128) NOT NULL,     /* 添加时间*/
    openid_xa TEXT(128) NOT NULL,    /* 设备名*/
    openid_tm TEXT(128) NOT NULL,      /* 位置*/
    openid_xd TEXT(128) NOT NULL, /* 设备类型*/ 
    userlibrary TEXT(128) NOT NULL,  /* 设备状态 */
    reg_date TIMESTAMP)";
    if ($conn->query($sql) === TRUE) {
        echo "创建用户成功";
    } else {
        echo "创建数据表错误: " . $conn->error;
    }
    $conn->close();
}

?>